﻿using Microsoft.AspNetCore.Mvc;
using WoodAdmin.Models;
using WoodAdmin.Services;
using SqlSugar;
using System.Linq;
using X.PagedList;
using System;

namespace WoodAdmin.Controllers
{
    public class SysGroupController : BaseController
    {
        private readonly SysGroupService _service;

        public SysGroupController(SysGroupService service)
        {
            _service = service;
        }

        #region 列表
        /// <summary>
        /// 列表
        /// </summary>
        /// <returns></returns>
        public IActionResult Index(SysGroup model,int page =1)
        {
            ViewBag.SearchModel = model;
            var list = _service.Queryable();
            if (!string.IsNullOrEmpty(model.Name))
            {
                list = list.Where(a => 
                    SqlFunc.Contains(a.Name, model.Name)||
                    SqlFunc.Contains(a.Title, model.Name)
                 ).ToList();
            }
            var pageList = list.ToPagedList(page, 15);
            return View(pageList);
        }
        #endregion

        #region 编辑
        /// <summary>
        /// 编辑/添加
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult AddEdit(int id)
        {
            SysGroup model = _service.FindEntity(id);
            if (model==null)
            {
                model = new SysGroup();
            }
            return View(model);
        }

        /// <summary>
        /// 编辑/添加
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult AddEdit(SysGroup model)
        {
            bool rs = false;
            if (model.ID>0)
            {
                var updateRs = _service.Update(model);
                if (updateRs)
                {
                    rs = true;
                }
            }
            else
            {
                model.Target="";
                model.Url="";
                model.DelFlag=0;
                model.SortNo=1;
                model.CreateMan=1;
                model.CreateTime=DateTime.Now;
                if (_service.Insert(model))
                {
                    rs = true;
                }
            }
            if (rs)
            {
                return JsonSuccess("保存成功！");
            }
           return JsonError("保存失败");
        }
        #endregion

        #region 删除
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public IActionResult Delete(int id)
        {
            if (_service.Delete(id))
            {
                return JsonSuccess("删除成功！");
            }
            return JsonError("删除失败");
        }
        #endregion
    }
}